import type {RouteRecordRaw} from 'vue-router'
import {pathToCamel} from '@/utils/tool'
import {adminRoutes, allRoutes} from "@/router"
import {h} from 'vue'
import type {IMenu} from "@/packages/admin/model/menu.interface";
import {adminRouterPath} from "@/router/config";

// 根据菜单列表，生成路由数据
export const generateRoutes = (menuList: IMenu[]): RouteRecordRaw[] => {
    const routerList: RouteRecordRaw[] = []

    const parentPath = allRoutes.path;
    const routerLevel1 = unid(adminRoutes, parentPath);

    menuList.forEach((menu: IMenu) => {
        let component
        let path;
        let menuPath = "";
        let breadcrumb = true;
        let iframe = false;
        let iframeUrl = "";
        //路由配置的网关地址
        let routePath = "";
        let multiplex = false;
        if (menu.children && menu.children.length > 0) {
            //component = () => import('@/packages/admin/layout/views/layout-blank.vue')
            component = () => import('@/packages/admin/layout/components/layout-content.vue')
            path = '/p/' + menu.menuId;
            routePath = path;
        } else {
            let routeFind = findRoute(menu.menuPath, routerLevel1)
            if (!routeFind) {
                routePath = "404";
                component = () => import('@/views/error-page/404.vue')
            } else {
                routePath = routeFind.path;
                component = routeFind.component;
                breadcrumb = routeFind.breadcrumb;
                //路由复用
                if (routeFind.meta) {
                    multiplex = routeFind.meta.multiplex
                }
            }
            if (menu.openType != "_blank" && menu.menuUrlType != "html" && menu.menuPath && menu.menuPath.substring(0, 1) != "/") {
                path = '/' + menu.menuPath
            } else {
                path = '' + menu.menuPath
            }

            //如果是iframe打开地址
            if (menu.menuUrlType == "html" && menu.openType != "_blank") {
                //const extlink = encodeURIComponent(path)
                //path = adminRouterPath + "/iframe?url=" + extlink + "&menuId=" + menu.menuId;
                iframeUrl = path;
                path = adminRouterPath + "/iframe?menuId=" + menu.menuId;
                iframe = true;
                routePath = path;

            }

            menuPath = path;

            if (routePath.includes("/:")) {
                multiplex = true
            }

            //如果是单页地址被外部打开，则要判断URL
            if (menu.menuUrlType == "spa" && menu.openType == "_blank" && !menu.menuPath?.startsWith("http") && !menu.menuPath?.startsWith("/#")) {
                menuPath = "/#" + menuPath;
            }

        }
        const route: RouteRecordRaw = {
            //path: path,
            path: routePath,
            name: pathToCamel(menuPath),
            component: component,
            children: [],
            meta: {
                url: menuPath,
                title: menu.menuName,
                icon: menu.icon,
                id: '' + menu.menuId,
                parentId: '' + menu.parentId ? menu.parentId : "",
                cache: true,
                isBlank: menu.openType === "_blank",
                breadcrumb: [],
                hidden: menu.hiddened == 1 ? true : false,
                iframe: iframe,
                iframeUrl: iframeUrl,
                menuUrlType: menu.menuUrlType,
                multiplex: multiplex //是否复用路由
            }
        }
        // 有子菜单的情况
        if (menu.children && menu.children.length > 0) {
            route.children?.push(...generateRoutes(menu.children))
        }
        routerList.push(route)

    })

    return routerList
}


function unid(arr: RouteRecordRaw[], parentPath: string): RouteRecordRaw[] {
    const routerList: RouteRecordRaw[] = []
    for (let item of arr) {
        if (item.children && item.children.length > 0) {
            routerList.push(...unid(item.children, item.path));
        } else {
            if (item.path.substring(0, 1) != "/") {
                item.path = parentPath + "/" + item.path;
            }
            routerList.push(item);
        }
    }
    return routerList;
}

// 从管理员的路由表中根据path查找
// 路由资料： http://www.17bigdata.com/book/vue.js/VUE-ROUTER/VUELuYouDuiXiangHeLuYouPiPei.html
/**
 * 相关路由正则：
 * /user/*any
 * /user/:username
 * /foo/*any/bar
 * @param path
 * @param routerLevel1
 */
const findRoute = (path?: string, routerLevel1?: RouteRecordRaw[]): any => {
    if (path && path.substring(0, 1) != "/") {
        path = "/" + path;
    }
    let fullPath = path;
    //删除path中的问号
    if (path && path?.includes("?")) {
        path = path.split("?")[0];
    }
    if (routerLevel1) {
        const routeRaw = routerLevel1.find(function (item) {
            //如果路由表的Path中有占位符，则要用占位符去匹配。这里用正则效率更新，但没找到合适的
            if (!item.path.includes("/:")) {
                return item.path == path;
                // //先正则，匹配 userId=(*) 类似的地址
                // let match: boolean = (item.path == path);
                // if (match) {
                //     return true;
                // }
                // //const regexStr = "\/webui\/test\\?userId=(\\w+)"; // 转义斜杠和问号字符，以及捕获组中的反斜杠字符
                // let regexStr = item.path.replaceAll("/", "\/");
                // regexStr = regexStr.replaceAll("?", "\\?");
                // const reg = new RegExp(regexStr);
                // match = reg.test(fullPath as string);
                // return match;
            } else {
                let routePaths = item.path.split("/");
                let menuPaths = path?.split("/");
                if (menuPaths && routePaths.length == menuPaths.length) {
                    // @ts-ignore
                    return macthPath(routePaths, menuPaths);
                }
            }
        })
        if (routeRaw) {
            return routeRaw
        } else {
            return null;
        }
    } else {
        return null;
    }
}

const macthPath = (routePaths: string[], menuPaths: string) => {
    let result = true;
    for (let i = 0; i < routePaths.length; i++) {
        if (!routePaths[i].includes(":")) {
            if (routePaths[i] != menuPaths[i]) {
                result = false;
            }
        }
    }
    return result;
}


// 获取扁平化路由，将多级路由转换成一级路由
export const getKeepAliveRoutes = (rs: RouteRecordRaw[], breadcrumb: string[]): RouteRecordRaw[] => {
    const routerList: RouteRecordRaw[] = []

    rs.forEach((item: any) => {
        if (item.meta.title) {
            breadcrumb.push(item.meta.title)
        }

        if (item.children && item.children.length > 0) {
            routerList.push(...getKeepAliveRoutes(item.children, breadcrumb))
        } else {
            //item.meta.breadcrumb.push(...breadcrumb)
            routerList.push(item)
        }

        //breadcrumb.pop()
    })
    return routerList
}
